package com.sa.app.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.sa.app.R;
import com.sa.app.activities.MainActivity;
import com.sa.app.objects.Item;
import com.sa.app.objects.Region;
import com.sa.app.objects.RegionImpl;
import com.sa.app.utilities.AsynchronousInsertUse;
import com.sa.app.utilities.MyApplication;

public class ItemsFragment extends Fragment implements OnItemClickListener {

	private List<Region> regions = new ArrayList<Region>();
	private ListView lista;
	private List<Item> listAdapter = new ArrayList<Item>();
	private Context cont;
	private int selectedItem;

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		this.cont = inflater.getContext();

		View v = inflater.inflate(R.layout.items_view, null);
		lista = (ListView) v.findViewById(R.id.listViewItems);
		lista.setAdapter(new MyAdapter(getActivity().getApplicationContext()));
		lista.setOnItemClickListener(this);

		this.setHasOptionsMenu(true);
		if (((ViewGroup) v.getParent()) != null) {
			((ViewGroup) v.getParent()).removeView(v);
		}
		return v;

	}

	public void initializeSpinner() {
		String allLocations = getString(R.string.all_locations);

		if (regions.isEmpty()) {
			regions.add(new RegionImpl(allLocations, null, null, null));
			regions.addAll(((MainActivity) getActivity()).getRegionsList());
		}

		List<CharSequence> elements = new ArrayList<CharSequence>();

		for (int i = 0; i < regions.size(); i++) {
			elements.add((CharSequence) regions.get(i).getName());

		}
		LayoutInflater factory = getActivity().getLayoutInflater();
		View vf = factory.inflate(R.layout.filter_spinner, null);

		ActionBar bar = getActivity().getActionBar();
		bar.setDisplayShowTitleEnabled(false);
		Spinner spinner = (Spinner) vf.findViewById(R.id.spinner);
		ArrayAdapter<CharSequence> barAdapter = new ArrayAdapter<CharSequence>(
				getActivity(), android.R.layout.simple_spinner_item, elements);
		barAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		spinner.setAdapter(barAdapter);
		spinner.setSelection(selectedItem);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				selectedItem = position;
				
				onResume();
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		((ViewGroup) spinner.getParent()).removeAllViews();
		bar.setDisplayShowCustomEnabled(true);

		bar.setCustomView((View) spinner);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {

		initializeSpinner();

		menuInflater.inflate(R.menu.items_fragment, menu);

	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		if (parent.getId() == R.id.listViewItems) {
			// con position podemos acceder al la posicion dentro de la lista
			// del adapter
			Item itemActual = (Item) ((ListAdapter) lista.getAdapter())
					.getItem(position);
			String NfcIDactual = itemActual.getNfcID();
			MainActivity ma = (MainActivity) getActivity();
			new AsynchronousInsertUse(ma, cont, (MyApplication) getActivity()
					.getApplication(), NfcIDactual, MyApplication.MAIN, "")
			.execute("");
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		
		
		
		String allLocations = getString(R.string.all_locations);
		if (regions.isEmpty()) {
			regions.add(new RegionImpl(allLocations, null, null, null));
			regions.addAll(((MainActivity) getActivity()).getRegionsList());
		}

		listAdapter = ((MainActivity) getActivity())
				.getItemsListFromRegion(regions.get(selectedItem));
		((MyAdapter) lista.getAdapter()).notifyDataSetChanged();

	}

	@Override
	public void onPause() {
		super.onPause();

		ActionBar bar = getActivity().getActionBar();

		bar.setDisplayShowTitleEnabled(true);
		bar.setDisplayShowCustomEnabled(false);

	}

	private class MyAdapter extends BaseAdapter {

		private Context context;

		public MyAdapter(Context c) {
			super();
			// No hace falta esta linea de abajo ya que el onResume() se ejecuta
			// incluso la primera vez que se inicia
			this.context = c;
		}

		public int getCount() {

			return listAdapter.size();
		}

		public Object getItem(int position) {

			return listAdapter.get(position);
		}

		public long getItemId(int position) {

			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater mInflater = LayoutInflater.from(context);
				convertView = mInflater.inflate(R.layout.list_view_row, null);// listview_fila,
				// null);
			}

			TextView alias;
			TextView manufacturer;
			TextView model;

			ImageView img1;
			Item item = listAdapter.get(position);
			// Llamamos a los recursos que vamos a utlizar
			alias = (TextView) convertView.findViewById(R.id.textViewAlias);// TextView01);
			manufacturer = (TextView) convertView
					.findViewById(R.id.textViewManufacturer);// TextView02);
			model = (TextView) convertView.findViewById(R.id.textViewModel);// TextView02);

			img1 = (ImageView) convertView.findViewById(R.id.imageViewDevice);// ImageView01);

			// Cambiamos los valores de las view
			// C_MAKE pos 0
			// C_MODEL pos 1
			// C_LOGO_MINI pos 2

			alias.setText(item.getAliasID());
			manufacturer.setText(item.getManufacturer());
			model.setText(item.getModel());

			try {
				Drawable d = new BitmapDrawable(getActivity()
						.getApplicationContext().getFilesDir()
						+ "/"
						+ item.getNfcID() + ".png");
				img1.setImageDrawable(d);

			} catch (Exception e) {
				
				img1.setImageDrawable(getResources().getDrawable(
						R.drawable.ic_launcher));
			}

			if (((ViewGroup) convertView.getParent()) != null) {
				((ViewGroup) convertView.getParent()).removeView(convertView);
			}
			return convertView;
		}
	}

	// Esto hace que no cuelgue la aplicación al cambiar de activity utilizando
	// la libreria de compatibilidad
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}

}